const gulp = require('gulp');
const babel = require('gulp-babel');
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
const cssnano = require('gulp-cssnano');
const concat = require('gulp-concat');
const source = require('vinyl-source-stream');
const shim = require('browserify-shim');
const less = require('gulp-less');
const babelify = require('babelify');
const browserify = require('browserify');
const rjs = require('requirejs');

gulp.task('convertJS', function(){
    return gulp.src('src/**/*.js')

        .pipe(babel({
            presets: ['es2015','react',"stage-0"]
        }))
        .pipe(uglify())
        // .pipe(concat('index.js'))
        .pipe(gulp.dest('dist'));
})
// gulp.task('rjs', function (cb) {
//     rjs.optimize({
//         baseUrl: "src/**/*.js",
//         mainConfigFile: "src/index.js",
//         preserveLicenseComments: false,
//         //去掉头部版权声明
//         removeCombined: false,
// //自动删除被合并过的文件
//     }, function (buildResponse) {
//         // console.log('build response', buildResponse);
//         cb();
//     }, cb)
// });


gulp.task('script:build', function() {
    browserify({
        entries: ["src/index.js"]
        })
        .transform(babelify, {
            presets: ['es2015', 'react']
        })
        .transform(shim)
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(gulp.dest('dist'));
});

gulp.task('buildLess', function () {
    return gulp.src('src/less/**/*.less')
        .pipe(less())
        .pipe(gulp.dest('dist/less'));
});

// 合并并压缩css
gulp.task('convertCSS', function(){
    return gulp.src('dist/less/**/*.css')
        .pipe(concat('./default/app.css'))
        .pipe(cssnano())
        .pipe(rename(function(path){
            path.basename += '.min';
        }))
        .pipe(gulp.dest('dist/css'));
})

gulp.task("browserify", function () {
    var b = browserify({
        entries: "dist/index.js"          //
    });

    return b.bundle()
        .pipe(source("bundle.js"))
        .pipe(gulp.dest("dist"));
});

// 监视文件变化，自动执行任务
gulp.task('watch', function(){
    gulp.watch('src/less/**/*.less', ['buildLess']);
    gulp.watch('dist/less/**/*.css', ['convertCSS']);
    gulp.watch('src/**/*.js', ['convertJS']);
})


gulp.task('start', ['buildLess','convertJS', 'convertCSS', 'watch']);
gulp.task('b', ['browserify']);
gulp.task('bs', ['script:build']);
